/** 
 * ================================================================================
 * 		Project		: Kompas Bola
 * 		File		: MainFragment.java
 * 		Description	: Fragment List Main
 * 		Called		: MainActivity.java
 * ================================================================================
 * */
package com.kompas.bola.application.fragment;

import java.util.List;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import java.util.ArrayList;
import android.os.AsyncTask;
import android.app.Activity;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebSettings.ZoomDensity;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.widget.AdapterView;
import android.view.LayoutInflater;
import com.google.analytics.tracking.android.Log;
import com.kompas.bola.application.R;
import android.widget.AdapterView.OnItemClickListener;
import com.kompas.bola.application.DetailActivity;
import com.kompas.bola.application.adapter.ListAdapter;
import com.kompas.bola.application.dao.Dao;
import com.kompas.bola.application.db.CrudHelper;
import com.kompas.bola.application.model.Content;
import com.kompas.bola.application.ui.ListUI;
import com.kompas.bola.application.ui.ListUI.OnLoadMoreListener;
import com.kompas.bola.application.ui.ListUI.OnRefreshListener;
import com.kompas.bola.application.utils.Constants;
/** =============================================================================== */
public class MainFragment extends Fragment{
	private ListUI list;	
	private int page 										= 1;
	private int initialPage 								= 1;
    private String _getPubDate;
	private ListAdapter adapter;
	private List<Content> list_data							= new ArrayList<Content>();
	private WebView imgProgressBar;
	private ProgressDialog pDialog;
	/** =========================================================================== */
	public MainFragment() {}
	/** =========================================================================== */
	@Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);			
		
		View view									= inflater.inflate(R.layout.main, container, false);
			
		list										= (ListUI) view.findViewById(R.id.list);
		adapter										= new ListAdapter(getActivity(), list_data);
		imgProgressBar								= (WebView) view.findViewById(R.id.imgProgressBarMain);

		String path									= "file:///android_asset/loading.html";
		imgProgressBar.loadUrl(path);	
		imgProgressBar.getSettings().setDefaultZoom(ZoomDensity.FAR);
		imgProgressBar.setVisibility(View.VISIBLE);			
		
		/** 
		 * Load Main Task */
		resetPage();
		/*progressBar.setVisibility(View.VISIBLE);*/
		new LoadTask().execute(isPage());		
				
		/**
		 * Pull Refresh Listener */
		list.setOnRefreshListener(new OnRefreshListener() {
			
			public void onRefresh() {
				list.prepareForRefresh();
				resetPage();
				new LoadRefreshTask().execute(isPage());
			}
		});		
		
		/** 
		 * LOAD MORE */
		list.setOnLoadMoreListener(new OnLoadMoreListener() {
			public void onLoadMore() {
					nextPage();
					new LoadMoreTask().execute();	
			}
		});	
		
		/**
		 * Pull Click Listener */		
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				// TODO Auto-generated method stub
				String guid 						= ((TextView) view.findViewById(R.id.guid)).getText().toString();						
				Intent detail 						= new Intent(getActivity(),DetailActivity.class);

		    	CrudHelper db						= new CrudHelper(getActivity());
		    	db.updateStatusByGuid(guid,Constants.AFTER_READ);
		    	
				detail.putExtra(Constants.GUID, guid);
				detail.putExtra(Constants.POSITION, position);
				detail.putExtra(Constants.KANAL, Constants.NULL);
				detail.putExtra(Constants.RELATED, Constants.NO);
				detail.putExtra(Constants.DETAIL_PARAM, Constants.DETAIL_MAIN);
				startActivityForResult(detail, 0);
			}
		});
		
		return view;				
	}
	/** =========================================================================== */
	private void nextPage() {
		this.page++;
	}
	/** =========================================================================== */
	public void resetPage() {
		this.page 								= this.initialPage;
	}
	/** =========================================================================== */
	int isPage(){
		return this.page;
	}
	/** =========================================================================== */
	private class LoadTask extends AsyncTask<Integer, Void, List<Content>>{
		protected void onPreExecute(){
		}

		@Override
		protected List<Content> doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			CrudHelper db						= new CrudHelper(getActivity());

			String status						= Constants.EMPTY;
			
			try {
				if(db.getCount() > 0){
					status						= db.checkUpdateNews();	
					Content bola				= Dao.getUpdateNews(status);
					
					try {
						if(bola.getKEY_MESSAGE().equalsIgnoreCase(Constants.RESULT_STATUS_SUCCESS)){
							if(!bola.getKEY_TOTAL().equalsIgnoreCase(Constants.ZERO)){
								try {
									if(db.getCount() > 0){
										db.delete();		
									}
									if(db.getCountRelated() > 0){
										db.deleteRelated();						
									}
								} catch (Exception e) {}
							}
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						Log.e(Constants.ERROR + " " + " Get Update News !!!");
					}
				}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				Log.e(Constants.ERROR + " " + " Get Count DB !!!");
			}			
						
			List<Content> list_content			= new ArrayList<Content>();
			List<Content> abstrak_list			= new ArrayList<Content>();
			String kanal						= Constants.NULL; // Set Param kanal NULL
			
			try {
				if(!(db.getCount() > 0)){
					int getPage					= params[0];
					abstrak_list				= Dao.getAllContent(getPage); // Sync Data
					for(int i=0; i < abstrak_list.size(); i++){
						Content bola 			= new Content();
						bola.setKEY_TITLE(abstrak_list.get(i).getKEY_TITLE());
						bola.setKEY_PHOTO_URL(abstrak_list.get(i).getKEY_PHOTO_URL());
						bola.setKEY_THUMB_URL(abstrak_list.get(i).getKEY_THUMB_URL());
						bola.setKEY_DESC(abstrak_list.get(i).getKEY_DESC());
						bola.setKEY_PUB_DATE(abstrak_list.get(i).getKEY_PUB_DATE());
						bola.setKEY_GUID(abstrak_list.get(i).getKEY_GUID());
						bola.setKEY_STATUS(Constants.BEFORE_READ);
					
						/** 
						 * SAVE DATA SQLITE */
						db.create(bola,kanal);						
					}	
				}else
					abstrak_list				= db.getAll(1,kanal); // Sync Data		
			} catch (Exception e) {
				// TODO Auto-generated catch block
				cancel(true);
				Log.e(Constants.ERROR + " " + " LoadTask Main Fragment !!!");
			}
				
			list_content.addAll(abstrak_list);
			return list_content;
		}	

		protected void onPostExecute(
				List<Content> result){
			if (!isCancelled()){
				if(result.size() > 0){					
					list_data.addAll(result);					
										
					if(list_data.get(0) != null){								
						list_data.get(0).setKEY_FIRST(true);
					}
					
					_getPubDate					= list_data.get(0).getKEY_PUB_DATE();
					
					try {
						adapter					= new ListAdapter(getActivity(), list_data);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						cancel(true);
					}
					
					adapter.notifyDataSetChanged();
					list.setAdapter(adapter);	

					imgProgressBar.setVisibility(View.GONE);		
				}else{
					list_data.isEmpty();
					adapter.notifyDataSetChanged();
					imgProgressBar.setVisibility(View.GONE);
				}
			}else
				return;		
			
		}
		
	}
	/** =========================================================================== */
	private class LoadRefreshTask extends AsyncTask<Integer, Void, List<Content>>{

		@Override
		protected List<Content> doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			CrudHelper db						= new CrudHelper(getActivity());

			try {
				if(db.getCount() > 0){
					db.delete();		
				}
				if(db.getCountRelated() > 0){
					db.deleteRelated();						
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				cancel(true);
			}		
			
			List<Content> list_content			= new ArrayList<Content>();
			List<Content> abstrak_list			= new ArrayList<Content>();
			String kanal						= Constants.NULL; // Set Param kanal NULL
			
			int getPage							= params[0];
			abstrak_list						= Dao.getAllContent(getPage);

			for(int i=0; i < abstrak_list.size(); i++){
				if(!(db.getByGuid(abstrak_list.get(i).getKEY_GUID()) > 0)){
					Content bola 			= new Content();
					bola.setKEY_TITLE(abstrak_list.get(i).getKEY_TITLE());
					bola.setKEY_PHOTO_URL(abstrak_list.get(i).getKEY_PHOTO_URL());
					bola.setKEY_THUMB_URL(abstrak_list.get(i).getKEY_THUMB_URL());
					bola.setKEY_DESC(abstrak_list.get(i).getKEY_DESC());
					bola.setKEY_PUB_DATE(abstrak_list.get(i).getKEY_PUB_DATE());
					bola.setKEY_GUID(abstrak_list.get(i).getKEY_GUID());
					bola.setKEY_STATUS(Constants.BEFORE_READ);
				
					/** 
					 * SAVE DATA SQLITE */
					db.create(bola,kanal);	
				}	
			}
			list_content.addAll(db.getAll(1,kanal));
			return list_content;
		}	

		protected void onPostExecute(
				List<Content> result){
			if (!isCancelled()){
				if(result.size() > 0){				
					resetPage();		
					list_data.removeAll(list_data);
					list_data.addAll(result);		

					if(list_data.get(0) != null){								
						list_data.get(0).setKEY_FIRST(true);
					}
					
					_getPubDate					= result.get(0).getKEY_PUB_DATE();
					
					try {
						adapter					= new ListAdapter(getActivity(), list_data);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						cancel(true);
					}
					
					list.setAdapter(adapter);	
					adapter.notifyDataSetChanged();
					list.resetHeader();
					list.onRefreshComplete();	
				}else{
					list_data.isEmpty();

					resetPage();
					adapter.notifyDataSetChanged();
					list.resetHeader();
					list.onRefreshComplete();		
				}				
			}
			
		}		
	}
	/** =========================================================================== */
	private class LoadRefreshTaskButton extends AsyncTask<Integer, Void, List<Content>>{
		@Override
		protected void onPreExecute(){
			pDialog								= new ProgressDialog(getActivity());
			pDialog.setMessage("loading...");
			pDialog.setOnCancelListener(new android.content.DialogInterface.OnCancelListener() {
				
				public void onCancel(DialogInterface dialog) {
					// TODO Auto-generated method stub
					pDialog.hide();
					Toast.makeText(getActivity(), Constants.PROCESS_CANCEL, Toast.LENGTH_SHORT).show();
					cancel(true);
				}
			});
			pDialog.setCancelable(true);
			pDialog.show();			
		}
		
		@Override
		protected List<Content> doInBackground(Integer... params) {
			// TODO Auto-generated method stub			
			
			List<Content> list_content			= new ArrayList<Content>();
			List<Content> abstrak_list			= new ArrayList<Content>();
			String kanal						= Constants.NULL; // Set Param kanal NULL
			if(!(isCancelled())){	
				CrudHelper db					= new CrudHelper(getActivity());
				
				try {
					if(db.getCount() > 0){
						db.delete();		
					}
					if(db.getCountRelated() > 0){
						db.deleteRelated();						
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					cancel(true);
				}		
				
				int getPage						= params[0];
				abstrak_list					= Dao.getAllContent(getPage);

				for(int i=0; i < abstrak_list.size(); i++){
					if(!(db.getByGuid(abstrak_list.get(i).getKEY_GUID()) > 0)){
						Content bola 			= new Content();
						bola.setKEY_TITLE(abstrak_list.get(i).getKEY_TITLE());
						bola.setKEY_PHOTO_URL(abstrak_list.get(i).getKEY_PHOTO_URL());
						bola.setKEY_THUMB_URL(abstrak_list.get(i).getKEY_THUMB_URL());
						bola.setKEY_DESC(abstrak_list.get(i).getKEY_DESC());
						bola.setKEY_PUB_DATE(abstrak_list.get(i).getKEY_PUB_DATE());
						bola.setKEY_GUID(abstrak_list.get(i).getKEY_GUID());
						bola.setKEY_STATUS(Constants.BEFORE_READ);
					
						/** 
						 * SAVE DATA SQLITE */
						db.create(bola,kanal);	
					}	
				}
				list_content.addAll(db.getAll(1,kanal));				
			}				
			return list_content;
		}	

		protected void onPostExecute(
				List<Content> result){
			if (!isCancelled()){
				if(result.size() > 0){				
					resetPage();		
					list_data.removeAll(list_data);
					list_data.addAll(result);		

					if(list_data.get(0) != null){								
						list_data.get(0).setKEY_FIRST(true);
					}
					
					_getPubDate					= result.get(0).getKEY_PUB_DATE();
					
					try {
						adapter					= new ListAdapter(getActivity(), list_data);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						cancel(true);
					}
					
					list.setAdapter(adapter);	
					adapter.notifyDataSetChanged();
					pDialog.hide();
				}else{
					list_data.isEmpty();

					resetPage();
					adapter.notifyDataSetChanged();
					pDialog.hide();
				}				
			}
			
		}		
	}
	/** =========================================================================== */
	private class LoadMoreTask extends AsyncTask<String, Void, List<Content>>{
		
		@Override
		protected List<Content> doInBackground(String... params) {
			// TODO Auto-generated method stub	
			CrudHelper db						= new CrudHelper(getActivity());
			try {
				if(!(db.getCount() > Constants.CONTENT_DB_LENGTH)){	
					return Dao.getAllContent(isPage());		
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				return null;
			}
			return null;
		}

		protected void onPostExecute(
				List<Content> result){
			if (!isCancelled()){

		    	CrudHelper db					= new CrudHelper(getActivity());
				String kanal					= Constants.NULL; // Set Param kanal NULL
				try {
					if(result.size() > 0){
						for(int i=0; i < result.size(); i++){
							if(!(db.getByGuid(result.get(i).getKEY_GUID()) > 0)){
								Content bola = new Content();
								bola.setKEY_TITLE(result.get(i).getKEY_TITLE());
								bola.setKEY_PHOTO_URL(result.get(i).getKEY_PHOTO_URL());
								bola.setKEY_THUMB_URL(result.get(i).getKEY_THUMB_URL());
								bola.setKEY_DESC(result.get(i).getKEY_DESC());
								bola.setKEY_PUB_DATE(result.get(i).getKEY_PUB_DATE());
								bola.setKEY_GUID(result.get(i).getKEY_GUID());
								bola.setKEY_STATUS(Constants.BEFORE_READ);
							
								/** 
								 * SAVE DATA SQLITE */
								db.create(bola,kanal);	
								list_data.add(bola);
							}	
						}
						
						try {
							adapter			= new ListAdapter(getActivity(), list_data);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							cancel(true);
						}
						
						Parcelable state 	= list.onSaveInstanceState();
						list.setAdapter(adapter);
						list.onRestoreInstanceState(state);						
						
						adapter.notifyDataSetChanged();	
						list.onLoadMoreComplete();			
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					list.onLoadMoreComplete();		
				}
			}				
		}
		
	}
	/** =========================================================================== */
    @Override
    public void onStop() {
        super.onStop();
		new LoadTask().cancel(true);
		new LoadMoreTask().cancel(true);
		new LoadRefreshTask().cancel(true);
    }
	/** =========================================================================== */
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);

        inflater.inflate(R.menu.main, menu);
    }
	/** =========================================================================== */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_refresh:
			resetPage();
			new LoadRefreshTaskButton().execute(isPage());
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	/** =========================================================================== */
}
